<template>
  <div>
    <div class="box">
      <div class="button">
        <div class="button_left">
          <el-button type="primary" :icon="Plus" @click="addUp()"
            >添加分支啊啊啊啊又一次 b的修改 好几次了 终于成了一次</el-button
          >
        </div>
        <div class="button_reght">
          <el-button plain :icon="Grid" />
          <el-button plain :icon="Search" />
        </div>
      </div>
      <div class="science_list">
        <el-table
          :data="
            scenicList.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <el-table :data="props.row.url">
                  <el-table-column label="ID" prop="id" />
                  <el-table-column label="名称" prop="name" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="ID">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.id }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="页面名称">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination
          :align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="scenicList.length"
        />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="newlyIncreased"
      :title="status == -1 ? '新增' : '编辑'"
      :before-close="resetChecked"
    >
      <el-scrollbar height="400px">
        <el-form :model="addition" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="角色名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="addition.name"
              autocomplete="off"
              placeholder="请输入角色名称"
              style="width: 90%"
            />
          </el-form-item>
          <el-form-item
            label="菜单列表"
            :label-width="formLabelWidth"
            prop="list"
          >
            <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              default-expand-all
              node-key="id"
              highlight-current
              :props="defaultProps"
              check-strictly
            />
            <!-- <el-select
              v-model="addition.list"
              multiple
              value-key="id"
              placeholder="请选择菜单"
              style="width: 90%"
              :on-change="out()"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select> -->
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addScenic(ruleFormRef)">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
            v-if="status == -1"
          >
            新增
          </el-button>
          <el-button
            type="primary"
            @click="submitFormRedact(ruleFormRef)"
            v-else
          >
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { reactive } from "vue";
import {
  Plus,
  Delete,
  Search,
  Grid,
  Upload,
  Operation
} from "@element-plus/icons-vue";
// import { CountTo } from "vue3-count-to";
import {
  powerIndex,
  roleIndex,
  roleAdd,
  roleDeletes,
  roleEdits
} from "@/api/role";
// import packpage from "../../../package.json";
// import { useI18n } from "vue-i18n";
// import { getResouceList } from "@/api/index";

// import { useStore } from "vuex";
// import axios from "axios";
import { genFileId, ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { roleList } from "@/pinia/role";
import { string } from "vue-types";
import { ElTree } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";
const user = roleList();
console.log(user.roleList);

// const components = ref({
//   Editor,
//   Toolbar
// });
const mode = ref("default");
const currentPage = ref(1);
const pageSize = ref(5);
const scenicList = ref([]);
const newlyIncreased = ref(false);

const status = ref();
const options = ref([]);
const formLabelWidth = "140px";
const addition = reactive({
  name: "",
  list: []
});
const treeRef = ref<InstanceType<typeof ElTree>>();
const loading = ref(true);
const treeData = ref([]);
const treeId = ref("0");
const addUp = () => {
  status.value = -1;
  newlyIncreased.value = true;
  addition.name = "";
  addition.list = [];
};
const resetChecked = (done: () => void) => {
  treeRef.value!.setCheckedKeys([], false);
  done();
};
const changeTree = (datalist, id, newArr) => {
  for (let i = 0; i < datalist.length; i++) {
    if (datalist[i].pid == id) {
      newArr.push(datalist[i]);
    }
  }
  for (let i = 0; i < newArr.length; i++) {
    newArr[i].children = [];
    changeTree(options.value, newArr[i].id, newArr[i].children);
    if (newArr[i].children.length == 0) {
      delete newArr.children;
    }
  }
};
powerIndex().then(res => {
  console.log(res);
  options.value = res.data.data;
  changeTree(options.value, treeId.value, treeData.value);
  console.log(treeData.value);
});
const defaultProps = {
  children: "children",
  label: "name"
};
const ruleFormRef = ref();
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur"
    }
  ],
  list: [
    {
      required: true,
      message: "请选择菜单",
      trigger: "blur"
    }
  ]
});
const submitForm = async formEl => {
  addition.list = treeRef.value!.getCheckedKeys(false).toString();
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(addition);
      addition.list = addition.list.toString();
      console.log(addition);
      //商品添加
      roleAdd(addition).then(res => {
        console.log(res);
        newlyIncreased.value = false;
        roleIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//商品编辑
const submitFormRedact = async formEl => {
  // newlyIncreased.value = false;
  console.log(!formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    addition.list = addition.list.toString();
    if (valid) {
      console.log(addition);
      roleEdits({
        ...addition,
        id: status.value
      }).then(res => {
        console.log(res); // 成功回调
        addition.list = [];
        newlyIncreased.value = false;
        roleIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
function addScenic(formEl) {
  newlyIncreased.value = false;
  if (!formEl) return;
  formEl.resetFields();
}
//请求列表信息
if (user.roleList.length) {
  loading.value = false;
  scenicList.value = user.roleList;
} else {
  user.getList().then(res => {
    loading.value = false;
    console.log(res);
    scenicList.value = res;
  });
}
//每页条数改变时触发 选择一页显示多少行
function handleSizeChange(val) {
  console.log(`每页 ${val} 条`);
  currentPage.value = 1;
  pageSize.value = val;
}
//当前页改变时触发 跳转其他页
function handleCurrentChange(val) {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
}
//编辑回显
function handleEdit(index, arr) {
  status.value = arr.id;
  newlyIncreased.value = true;
  roleIndex({ id: arr.id }).then(res => {
    console.log(res);
    if (res.data.code == 0) {
      ElMessage.error(res.data.err);
    } else {
      addition.name = res.data.data[0].name;
      const arr = res.data.data[0].list.split(",");
      const list = [];
      for (let i = 0; i < arr.length; i++) {
        list[i] = parseInt(arr[i]);
      }
      console.log(list);
      // setTimeout(() => {
      treeRef.value!.setCheckedKeys(list, false);
      // }, 200);
    }
  });
}
//删除
function handleDelete(index, arr) {
  console.log(index);
  console.log(arr);
  roleDeletes({ id: arr.id }).then(res => {
    console.log(res); // 成功回调
    roleIndex().then(res => {
      scenicList.value = res.data.data;
    });
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}
</script>

<style scoped>
.box {
  background-color: white;
  padding: 20px;
}
.button {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.paging {
  width: 100%;
  text-align: center;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
